package com.rxnetwork.sample.utils.network

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo

/**
 * Created by xiaocode on 2016/9/1.
 * 检查当前网络
 */
object AppNetworkAvailable {

    /**
     * 检查当前网络是否可用

     * @return
     */
    fun isNetworkAvailable(context: Context): Boolean {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        if (connectivityManager == null) {
            return false
        } else {
            // 获取NetworkInfo对象
            val networkInfo = connectivityManager.allNetworkInfo

            if (networkInfo != null && networkInfo.size > 0) {
                for (i in networkInfo.indices) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].state == NetworkInfo.State.CONNECTED) {
                        return true
                    }
                }
            }
        }
        return false
    }
}
